/******* 模板布局解析相关Util ******/
import React from 'react';
import * as _ from './common';
import src from './source';
import WfForm_Public from "./interface";

//布局解析时生成行头
export const convertRowHeads = (rowHeads) =>{
    let arr = [];
    _.forIn(rowHeads, (v,k) =>{
        arr.push({id:k.substring(4), height:v+"px"});
    });
    arr = arr.sort((a,b)=>{
        return parseInt(a.id)-parseInt(b.id);
    });
    return arr;
}

//布局解析时生成列头并控制Table宽度
export const convertColHeads = (colHeads, symbol, layouttype, tableStyle, allowXScroll, isSeniorSet) =>{
    if(typeof allowXScroll === "undefined")
        allowXScroll = false;
    let hasPercent = false;
    let hasAutoAdapt = false;
    let totalPx = 0;
    let totalPercent = 0;
    _.forIn(colHeads, (v,k) =>{
        v = v.toString();
        if(v==="0%" || v.indexOf("*") > -1)
            v = "*";
        if(v.indexOf("*") > -1){
            hasAutoAdapt = true;
        }else if(v.indexOf("%") > -1){
            hasPercent = true;
            totalPercent += parseFloat(v.replace("%",""));
        }else{  //绝对宽度
            totalPx += parseFloat(v);
        }
    });

    const isMobileLayout = layouttype === 2;
    const isDetail = symbol.indexOf("detail_") > -1;
    const isMain = symbol === "main";
    let needTransPercent = false;
    //标签页、明细表不开启横向滚动条、移动模板主界面等情况，需转百分比宽度
    if(!hasAutoAdapt && (symbol.indexOf("tab_") > -1 || (isMobileLayout && isMain) || (isDetail && !allowXScroll)))
        needTransPercent = true;
    //批量打印特殊处理，列宽全转百分比，如是绝对宽度布局则把总宽度限定给iframe宽度
    const { urlParams={},baseParam } = src.globalStore;
    if(layouttype === 1 && isMain && urlParams.isBatchPrint === "true"){
        needTransPercent = true;
        if(!hasAutoAdapt && !hasPercent && totalPx <= 1000)
            window.jQuery(`iframe#request_${baseParam.requestid}`,window.parent.document).width(totalPx+20);
    }
    //外层table宽度设置
    if(hasPercent || hasAutoAdapt || needTransPercent)
        tableStyle["width"] = "100%";
    else if(isMain || allowXScroll)
        tableStyle["width"] = totalPx+"px";
    else
        tableStyle["width"] = "auto";
    let validPercent = 100;
    if(isDetail && !allowXScroll && !isSeniorSet)     //低级模式预留6%给序号列
        validPercent = 94;
    let arr = [];
    _.forIn(colHeads, (v,k) =>{
        v = v.toString();
        let colWidth = (v==="0%" || v.indexOf("*") > -1) ? "*": v;
        if(needTransPercent && colWidth.indexOf("%") === -1){
            colWidth = (parseFloat(colWidth)/totalPx) * (validPercent-totalPercent);
            colWidth = colWidth.toFixed(2)+"%";
        }
        if(colWidth.indexOf("%") === -1 && colWidth !== "*")
            colWidth += "px";
        arr.push({id:k.substring(4), width:colWidth});
    });
    arr = arr.sort((a,b)=>{
        return parseInt(a.id)-parseInt(b.id);
    });
    return arr;
}

//转换为单元格map
export const convertEcMap = (ecArr) =>{
    let ecMap = {};
    ecArr && ecArr.map(v =>{
        ecMap[v.id] = v;
    });
    return ecMap;
}

//解析模板背景图、悬浮图
export const parseLayoutImage = (layout, tableStyle, trArr) =>{
    if(!!layout.backgroundImage){   //背景图
        tableStyle["background-image"] = `url(${layout.backgroundImage})`;
        tableStyle["background-repeat"] = "no-repeat";
    }
    const floatImgArr = layout.floatingObjectArray && layout.floatingObjectArray.floatingObjects;
    if(!!floatImgArr){   //悬浮图
        let imgArr = new Array();
        floatImgArr.map(imgInfo =>{
            const imgStyle = {width:imgInfo.width, height:imgInfo.height, top:imgInfo.y, left:imgInfo.x};
            imgArr.push(React.createElement("img", {src:imgInfo.src, className:"floatImg", style:imgStyle}));
        });
        const columnSize = Object.keys(layout.colheads).length;
        trArr.push(React.createElement("tr", {style:{height:"0px"}}, [
            React.createElement("td", {colSpan:columnSize, className:"floatImgTd"}, imgArr)
        ]));
    }
}

const cellBelRowSpan = {};

//判断单元格是否属于被行合并的单元格
export const judgeCellBelRowSpan = (symbol,rowid,colid,ecMap) =>{
    const key = `${symbol}_${rowid}_${colid}`;
    if(key in cellBelRowSpan)
        return cellBelRowSpan[key];
    let belong = false;
    for(let j=colid; j>=0 && !belong; j--) {
        for(let i=rowid-1; i>=0&&!belong; i--) {
            const cellObj = ecMap[i+","+j];
            const rowSpan = cellObj ? (cellObj.rowspan || 1) : 0;
            const colSpan = cellObj ? (cellObj.colspan || 1) : 0;
            if(rowSpan>1 && rowSpan>=(rowid-i+1) && colSpan>=(colid-j+1))   //单元格属于被上方行合并的单元格
                belong = true;
        }
    }
    cellBelRowSpan[key] = belong;   //缓存存储，降低布局很大时的遍历性能
    return belong;
}

//判断明细布局是否含有列隐藏
export const judgeDetailContainColHide = (colattrs) =>{
    let contain = false;
    _.forIn(colattrs, (v,k) =>{
        if(v && v.hide === "y"){
            contain = true;
            return false;
        }
    });
    return contain;
}

export const getCellAttr = (cellObj, colCusAttr, rowHeight, isCardEdit=false) =>{
    let cellAttr = {};
    let tdStyle = {};
    let divStyle = {};
    let tdClass = "";
    const financial = cellObj && cellObj.financial;
    //财务格式所在单元格div增加高度100%
    if(financial && financial.indexOf("2-") > -1){
        tdStyle["height"] = rowHeight+"px";
        divStyle["height"] = "100%";
        divStyle["padding"] = "0px";
    }
    //列自定义属性
    if(colCusAttr && colCusAttr.hide === "y" && (!isCardEdit || (isCardEdit && colCusAttr.isDetailCardShow != "1")))
        tdClass += " detail_hide_col";
    if(colCusAttr && colCusAttr.class)
        tdClass += " "+colCusAttr.class;
    //单元格自定义属性(放最后可覆盖之前的CSS)
    const cusattrs = cellObj && cellObj.attrs;
    if(cusattrs && cusattrs.class)
        tdClass += " "+ `${cusattrs.class}_swap`;
    cusattrs && appendCusAttrObj(cellAttr, cusattrs, divStyle);
    
    cellAttr.tdStyle = tdStyle;
    cellAttr.tdClass = _.trim(tdClass);
    cellAttr.divStyle = divStyle;
    return cellAttr;
}

export const getMcCellAttr = (cellObj) =>{
    let mcCellAttr = {};
    let spanStyle = {};
    //自定义属性
    const cusattrs = cellObj && cellObj.attrs;
    cusattrs && appendCusAttrObj(mcCellAttr, cusattrs, spanStyle);
    mcCellAttr.spanStyle = spanStyle;
    return mcCellAttr;
}

export const getRowAttr = (rowHeight, rowCusAttr) =>{
    let rowAttr = {};
    rowAttr.id = rowCusAttr ? rowCusAttr.id : "";
    rowAttr.name = rowCusAttr ? rowCusAttr.name : "";
    rowAttr.trClass = rowCusAttr ? rowCusAttr.class : "";
    let trStyle = {};
    trStyle["height"] = rowHeight;
    if(rowCusAttr && rowCusAttr.hide === "y")
        trStyle["display"] = "none";
    if(rowCusAttr && rowCusAttr.style)
        appendCusAttrStyle(trStyle, rowCusAttr.style);
    rowAttr.trStyle = trStyle;
    return rowAttr;
}

const appendCusAttrObj = (obj, cusattrs, styleObj) =>{
    !_.isEmpty(cusattrs) && _.forIn(cusattrs, (v,k) =>{
        if(k === "hide"){
            if(v === "y")
                styleObj["display"] = "none";
        }else if(k === "id"){
            obj.cusid = v;
        }else if(k === "name"){
            obj.cusname = v;
        }else if(k === "class"){
            obj.cusclass = v;
        }else if(k === "style"){
            appendCusAttrStyle(styleObj, v);
        }else{  //自定义属性加data-并且变小写
            obj[`data-${k.toLowerCase()}`] = v;
        }
    });
}

const appendCusAttrStyle = (styleObj, cusstylestr) => {
    let styleArr = cusstylestr.split(";");
    for(let i=0; i<styleArr.length; i++){
        let item = styleArr[i];
        let itemArr = item.split(":");
        if(itemArr.length >= 2)
            styleObj[itemArr[0]] = itemArr[1];
    }
    return styleObj;
}

//根据解析的自定义属性生成单元格属性
export const buildCellAttr = (tdCellAttr, className, style) =>{
    let cellAttr = {};
    if(className)
        cellAttr["className"] = className;
    if(style)
        cellAttr["style"] = style;
    if(!tdCellAttr)
        return cellAttr;
    for(let key in tdCellAttr){
        const value = tdCellAttr[key];
        if(key === "cusid")
            cellAttr["id"] = value;
        else if(key === "cusname")
            cellAttr["name"] = value;
        else if(key.length > 5 && key.substring(0,5) === "data-")     //自定义属性
            cellAttr[key] = value;
    }
    return cellAttr
}

//替换IFrame动态参数
export const getDynamicFieldValueSrc = (dynamicFieldnames,temp_src) =>{
    let src = temp_src;
    _.forEach(dynamicFieldnames, (value) =>{
        let repalceReg = '\\$\\[' + value + '\\]\\$';
        src = src.replace(new RegExp(repalceReg, "gm"), WfForm_Public.getFieldValue(WfForm_Public.convertFieldNameToId(value)));
    });
    return src;
}